package com.app.studyroom;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.studyroom.adapter.SeatRateAdapter;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.message.MessageIndexResponse;
import com.app.studyroom.api.model.message.SeatRateItem;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeActivity extends BaseActivity {

    private LinearLayout btnSeatStatus, btnLearningRanking, btnLogin, btnContactAdmin, btnStudyroomRules, btnHelp, btnDoorAccess;
    private LinearLayout layout_hide;
    private TextView tvSystem, tvNotice, tvWarning;
    private RecyclerView rvSeatRate;

    // 定时刷新
    private final long REFRESH_INTERVAL_MS = 60 * 1000;
    private final Handler refreshHandler = new Handler();
    private final Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            fetchMessageData();
            fetchSeatRateData();
            refreshHandler.postDelayed(this, REFRESH_INTERVAL_MS);
        }
    };

    // 锁屏逻辑
    private Handler lockHandler = new Handler();
    private Runnable lockRunnable;
    private boolean isForeground = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        btnSeatStatus = findViewById(R.id.seat_status);
        btnLearningRanking = findViewById(R.id.btnLearningRanking);
        btnLogin = findViewById(R.id.person_login);
        btnContactAdmin = findViewById(R.id.contact_admin);
        btnStudyroomRules = findViewById(R.id.studyroom_rules);
        btnHelp = findViewById(R.id.help_please);
        btnDoorAccess = findViewById(R.id.door_access);

        tvSystem = findViewById(R.id.tv_system_message);
        tvNotice = findViewById(R.id.tv_notice_message);
        tvWarning = findViewById(R.id.tv_warning_message);
        tvWarning.setSelected(true);

        rvSeatRate = findViewById(R.id.rvSeatRate);
        layout_hide = findViewById(R.id.layout_hide);
        layout_hide.setVisibility(View.GONE);

        btnSeatStatus.setOnClickListener(v -> startActivity(new Intent(this, ClassActivity.class).putExtra("enableReservation", false)));
        btnLearningRanking.setOnClickListener(v -> startActivity(new Intent(this, LearningRankingActivity.class)));
        btnLogin.setOnClickListener(v -> startActivity(new Intent(this, LoginActivity.class)));
        btnContactAdmin.setOnClickListener(v -> startActivity(new Intent(this, ContactAdminActivity.class)));
        btnStudyroomRules.setOnClickListener(v -> startActivity(new Intent(this, StudyRoomRulesActivity.class)));
        btnHelp.setOnClickListener(v -> { /* TODO */ });
        btnDoorAccess.setOnClickListener(v -> startActivity(new Intent(this, AccessControlActivity.class)));

        fetchMessageData();
        fetchSeatRateData();

        lockRunnable = () -> {
            if (!isTaskRoot() || isFinishing()) {
                Log.d("HomeActivity", "当前不是根页面，跳过锁屏");
                return;
            }
            Log.d("HomeActivity", "进入锁屏计时器逻辑：启动熄屏遮罩");

            Intent intent = new Intent(this, AppLockActivity.class);
            intent.putExtra("source", "HomeActivity");
            startActivity(intent);
        };

        resetLockTimer();
        Log.d("HomeActivity", "onCreate: 恢复定时器开始计时");
    }

    @Override
    protected void onResume() {
        super.onResume();
        isForeground = true;
        refreshHandler.post(refreshRunnable);
        if (isTaskRoot()) {
            resetLockTimer();
            Log.d("HomeActivity", "onResume: 恢复定时器开始计时");
        } else {
            Log.d("HomeActivity", "onResume: 正在关闭熄屏定时器");
            lockHandler.removeCallbacks(lockRunnable);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isForeground = false;
        Log.d("HomeActivity", "onPause: 正在关闭熄屏定时器");
        refreshHandler.removeCallbacks(refreshRunnable);
        lockHandler.removeCallbacks(lockRunnable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isForeground = false;
        Log.d("HomeActivity", "onDestroy: 正在关闭熄屏定时器");
        lockHandler.removeCallbacks(lockRunnable);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(isForeground){
            resetLockTimer(); // 用户有操作，重置锁屏计时
            Log.d("HomeActivity", "dispatchTouchEvent: 是顶层页");
            Log.d("HomeActivity", "dispatchTouchEvent: 恢复定时器开始计时");
        }else{
            Log.d("HomeActivity", "dispatchTouchEvent: 不是顶层页");
        }
        return super.dispatchTouchEvent(ev);
    }

    private void resetLockTimer() {
        lockHandler.removeCallbacks(lockRunnable);
        Log.d("HomeActivity", "resetLockTimer: 清除旧的定时器");

        long timeout = getLockTimeout();
        if (timeout < 0) {
            Log.d("HomeActivity", "永不休眠，跳过计时器");
            return;
        }

        long triggerTime = System.currentTimeMillis() + timeout;
        String triggerTimeStr = new java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault()).format(new java.util.Date(triggerTime));
        Log.d("HomeActivity", "用户操作：重置计时器，将在 " + triggerTimeStr + " 触发锁屏");
        lockHandler.postDelayed(lockRunnable, timeout);
    }

    private long getLockTimeout() {
        SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
        return prefs.getLong("sleepTimeoutMillis", 900_000L);
    }
//    private long getLockTimeout() {
//        // 🧪 测试用：设置为15秒，正常使用时建议改回30_000L或从设置中获取
//        return 15_000L;
//    }

    private void fetchMessageData() {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getMessageIndex().enqueue(new Callback<ApiResponse<MessageIndexResponse>>() {
            @Override
            public void onResponse(Call<ApiResponse<MessageIndexResponse>> call, Response<ApiResponse<MessageIndexResponse>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                    MessageIndexResponse data = response.body().getData();
                    tvSystem.setText(buildMessageBlock(data.getSystemMessage()));
                    tvNotice.setText(buildMessageBlock(data.getNoticeMessage()));
                    tvWarning.setText(buildMessageBlock(data.getWarningMessage()));
                } else {
                    Log.e("HomeActivity", "获取消息失败，code=" + response.code());
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<MessageIndexResponse>> call, Throwable t) {
                Log.e("HomeActivity", "消息接口请求失败", t);
            }
        });
    }

    private void fetchSeatRateData() {
        rvSeatRate.setLayoutManager(new GridLayoutManager(this, 4));
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        apiService.getSeatRateList().enqueue(new Callback<ApiResponse<List<SeatRateItem>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<SeatRateItem>>> call, Response<ApiResponse<List<SeatRateItem>>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 200) {
                    List<SeatRateItem> list = response.body().getData();
                    rvSeatRate.setAdapter(new SeatRateAdapter(list));
                } else {
                    Log.e("HomeActivity", "预约率数据无效，code=" + response.code());
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<SeatRateItem>>> call, Throwable t) {
                Log.e("HomeActivity", "获取教室预约率失败", t);
            }
        });
    }

    private String buildMessageBlock(List<MessageIndexResponse.MessageGroup> list) {
        if (list == null || list.isEmpty()) return "暂无消息";
        StringBuilder sb = new StringBuilder();
        for (String msg : list.get(0).message) {
            sb.append("• ").append(msg).append("\n");
        }
        return sb.toString();
    }
}
